package com.cloud.core.config;


import feign.FeignException;
import feign.Response;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
 * @author admin
 */
@Slf4j
public class FeignResponseDecoder extends SpringDecoder {
    public FeignResponseDecoder(ObjectFactory<HttpMessageConverters> messageConverters,ObjectProvider<HttpMessageConverterCustomizer> customizers) {
        super(messageConverters,customizers);
    }

    @Override
    public Object decode(final Response response, Type type) throws IOException, FeignException {
        Map<String, Collection<String>> headers = response.headers();
        ServletRequestAttributes servletRequestAttributes = currentRequestAttributes();
        if (servletRequestAttributes != null) {
            HttpServletResponse resp = servletRequestAttributes.getResponse();
            if (headers != null && resp != null) {
                headers.forEach((key, values) -> {
                    values.forEach(value -> {
                        resp.addHeader(key, value);
                    });
                });
            }
        }
        return super.decode(response, type);
    }

    private static ServletRequestAttributes currentRequestAttributes() {
        RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
        if (!(requestAttr instanceof ServletRequestAttributes)) {
            log.error("Current request is not a servlet request");
            return null;
        }
        return (ServletRequestAttributes) requestAttr;
    }
}
